package com.teamwings.config.redis;

import com.teamwings.util.CodeContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * redis
 * 需要动态增加前缀，如：1001:tenant_1:xxx:xxx:xxx
 */
@Slf4j
public class JRedisCacheWriter implements RedisCacheWriter {

	private final RedisConnectionFactory connectionFactory;
	private final Duration sleepTime;

	public JRedisCacheWriter(RedisConnectionFactory connectionFactory) {
		this(connectionFactory, Duration.ZERO);
	}

	public JRedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) {
		Assert.notNull(connectionFactory, "ConnectionFactory must not be null!");
		Assert.notNull(sleepTime, "SleepTime must not be null!");
		this.connectionFactory = connectionFactory;
		this.sleepTime = sleepTime;
	}

	/**
	 * 前缀
	 * @param key -
	 * @return -
	 */
	private static byte[] prefix(byte[] key) {
		String var1 = new String(key);
		var1 = CodeContext.getPrefix() + var1;
		return var1.getBytes();
	}

	@Override
	public void put(String name, byte[] key, byte[] value, @NotNull Duration ttl) {
		Assert.notNull(name, "Name must not be null!");
		Assert.notNull(key, "Key must not be null!");
		Assert.notNull(value, "Value must not be null!");
		byte[] var2 = prefix(key);
		log.info("redis put key：" + new String(var2));
		this.execute(name, (connection) -> {
			if (shouldExpireWithin(ttl)) {
				connection.set(var2, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
			} else {
				connection.set(var2, value);
			}
			return "OK";
		});
	}

	@Override
	public byte[] get(String name, byte[] key) {
		Assert.notNull(name, "Name must not be null!");
		Assert.notNull(key, "Key must not be null!");
		byte[] var2 = prefix(key);
		log.info("redis get key：" + new String(var2));
		return this.execute(name, (connection) -> connection.get(var2));
	}

	@Override
	public byte[] putIfAbsent(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
		Assert.notNull(name, "Name must not be null!");
		Assert.notNull(key, "Key must not be null!");
		Assert.notNull(value, "Value must not be null!");
		byte[] var2 = prefix(key);
		log.info("redis putIfAbsent key：" + new String(var2));
		return (byte[])this.execute(name, (connection) -> {
			if (this.isLockingCacheWriter()) {
				this.doLock(name, connection);
			}

			Object var7;
			try {
				boolean put;
				if (shouldExpireWithin(ttl)) {
					put = connection.set(var2, value, Expiration.from(ttl), RedisStringCommands.SetOption.ifAbsent());
				} else {
					put = connection.setNX(var2, value);
				}

				if (!put) {
					byte[] var11 = connection.get(var2);
					return var11;
				}

				var7 = null;
			} finally {
				if (this.isLockingCacheWriter()) {
					this.doUnlock(name, connection);
				}

			}

			return (byte[])var7;
		});
	}

	/**
	 * 删除所有相关前缀keyName*，如keyName1，keyName2，keyName3...
	 * @param name -
	 * @param key -
	 */
	@Override
	public void remove(String name, byte[] key) {
		Assert.notNull(name, "Name must not be null!");
		Assert.notNull(key, "Key must not be null!");
		byte[] var2 = prefix(key);
		String keyString = new String(var2);
		log.info("redis remove key：" + new String(var2));
		if(keyString.endsWith("*")){
			execute(name, connection -> {
				// 获取某个前缀所拥有的所有的键，某个前缀开头，后面肯定是*
				Set<byte[]> keys = connection.keys(var2);
				int delNum = 0;
				for (byte[] keyByte : keys) {
					delNum += connection.del(keyByte);
				}
				return delNum;
			});
		} else {
			this.execute(name, (connection) -> connection.del(new byte[][]{var2}));
		}
	}

	@Override
	public void clean(String name, byte[] pattern) {
		Assert.notNull(name, "Name must not be null!");
		Assert.notNull(pattern, "Pattern must not be null!");
		this.execute(name, (connection) -> {
			boolean wasLocked = false;

			try {
				if (this.isLockingCacheWriter()) {
					this.doLock(name, connection);
					wasLocked = true;
				}

				byte[][] keys = (byte[][])((Set) Optional.ofNullable(connection.keys(pattern)).orElse(Collections.emptySet())).toArray(new byte[0][]);
				if (keys.length > 0) {
					connection.del(keys);
				}
			} finally {
				if (wasLocked && this.isLockingCacheWriter()) {
					this.doUnlock(name, connection);
				}

			}

			return "OK";
		});
	}

	void lock(String name) {
		this.execute(name, (connection) -> {
			return this.doLock(name, connection);
		});
	}

	void unlock(String name) {
		this.executeLockFree((connection) -> {
			this.doUnlock(name, connection);
		});
	}

	private Boolean doLock(String name, RedisConnection connection) {
		return connection.setNX(createCacheLockKey(name), new byte[0]);
	}

	private Long doUnlock(String name, RedisConnection connection) {
		return connection.del(new byte[][]{createCacheLockKey(name)});
	}

	boolean doCheckLock(String name, RedisConnection connection) {
		return connection.exists(createCacheLockKey(name));
	}

	private boolean isLockingCacheWriter() {
		return !this.sleepTime.isZero() && !this.sleepTime.isNegative();
	}

	private <T> T execute(String name, Function<RedisConnection, T> callback) {
		RedisConnection connection = this.connectionFactory.getConnection();

		try {
			this.checkAndPotentiallyWaitUntilUnlocked(name, connection);
			return callback.apply(connection);
		} finally {
			connection.close();
		}

	}

	private void executeLockFree(Consumer<RedisConnection> callback) {
		RedisConnection connection = this.connectionFactory.getConnection();

		try {
			callback.accept(connection);
		} finally {
			connection.close();
		}

	}

	private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection connection) {
		if (this.isLockingCacheWriter()) {
			try {
				while(this.doCheckLock(name, connection)) {
					Thread.sleep(this.sleepTime.toMillis());
				}

			} catch (InterruptedException var4) {
				Thread.currentThread().interrupt();
				throw new PessimisticLockingFailureException(String.format("Interrupted while waiting to unlock cache %s", name), var4);
			}
		}
	}

	private static boolean shouldExpireWithin(@Nullable Duration ttl) {
		return ttl != null && !ttl.isZero() && !ttl.isNegative();
	}

	private static byte[] createCacheLockKey(String name) {
		return (name + "~lock").getBytes(StandardCharsets.UTF_8);
	}
}
